package com.walsai.pcsys.web.controller;

import java.io.File;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.walsai.pcsys.core.model.Problem;
import com.walsai.pcsys.core.model.Solution;
import com.walsai.pcsys.core.model.SolutionPK;
import com.walsai.pcsys.core.model.User;
import com.walsai.pcsys.core.service.ProblemManager;
import com.walsai.pcsys.core.service.SolutionManager;

public class SubmitSolutionController extends SimpleFormController {

	private ProblemManager problemManager;
	private SolutionManager solutionManager;

	public void setProblemManager(ProblemManager problemManager) {
		this.problemManager = problemManager;
	}

	public void setSolutionManager(SolutionManager solutionManager) {
		this.solutionManager = solutionManager;
	}
	protected void initBinder(HttpServletRequest req,
			ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Solution s = (Solution) command;
		Problem p = this.problemManager.get(Long.valueOf(request.getParameter("problemId")));
		HttpSession session = request.getSession();
		User u = (User) session.getAttribute("userInfo");
		SolutionPK sPK = new SolutionPK();
		s.setSolutionPK(sPK);
		s.getSolutionPK().setUser(u);
		s.getSolutionPK().setProblem(p);
		s.setSubmitDate(new java.sql.Timestamp(new java.util.Date().getTime()));
		Solution sSaved = this.solutionManager.save(s);
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile solutionFile = multipartRequest.getFile("codeFile");
			File destination = null;
			destination = new File("target/web-1.0-SNAPSHOT/solutions/"+sSaved.getSolutionPK().getProblem().getId()+"-"+
					sSaved.getSolutionPK().getUser().getUsername()+".sol");
			solutionFile.transferTo(destination);
			if(((int)(Math.random()*2) == 0)){
				destination.delete();
				this.solutionManager.remove(sSaved.getSolutionPK());
				return new ModelAndView("incorrect");
			} else {
				return new ModelAndView("correct");
			}
		} catch (Exception e) {
			this.solutionManager.remove(sSaved.getSolutionPK());
			return new ModelAndView("failed");
		} finally{

		}

	}

}
